<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/4 0004
 * Time: 17:42
 */

namespace app\common\model;


use think\Exception;

class Category extends BaseModel
{

    /**
     * 关联中间表获取品牌
     * @return \think\model\relation\HasMany
     */
    public function brands() {
        return $this->hasMany('CategoryAndBrand');
    }

    /**
     * 创建或者编辑分类
     * @param $param
     * @param int $id
     * @return \think\response\Json
     */
    public static function createOrUpdateCategory($param, $id = 0) {
        try {
            if ($id > 0) {
                // 编辑
                $banner = self::get($id);
                if (!$banner) {
                    throw new Exception('分类不存在');
                }
                $check_banner = self::where('name', '=', $param['name'])->where('id', 'neq', $id)->find();
                if ($check_banner) {
                    throw new Exception('分类名已存在');
                }
                $banner->save($param);
            } else {
                $check_banner = self::where('name', '=', $param['name'])->find();
                if ($check_banner) {
                    throw new Exception('分类名已存在');
                }
                // 添加
                self::create($param);
            }
            return return_data('success');
        } catch (Exception $e) {
            return return_data($e->getMessage(), 1);
        }
    }

    /**
     * 按级获取所有分类
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function get_category() {
        $items = self::select()->toArray();
        foreach ($items as $item)
        {
            $tmpMap[$item['id']] = $item;
        }

        // print_r($tmpMap);
        foreach ($items as $item)
        {
            if (isset($tmpMap[$item['pid']]))
            {
                $tmpMap[$item['pid']]['childrens'][] = &$tmpMap[$item['id']];
            }
            else
            {
                $tree[] = &$tmpMap[$item['id']];
            }
        }
        return $tree;
    }
}